package com.usdt.system.service.impl.cp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usdt.common.core.domain.entity.SysDictData;
import com.usdt.common.core.domain.entity.SysRole;
import com.usdt.common.core.domain.entity.SysUser;
import com.usdt.common.exception.ServiceException;
import com.usdt.common.utils.bean.BeanUtil;
import com.usdt.system.cp.utils.UserAndDeptUtils;
import com.usdt.system.domain.cp.CallbackRecordEntity;
import com.usdt.system.domain.cp.VisitCustomerInfoEntity;
import com.usdt.system.domain.cp.VisitRecordEntity;
import com.usdt.system.domain.cp.VisitRegisterEntity;
import com.usdt.system.domain.req.BatchTransferOutReqVO;
import com.usdt.system.domain.req.CallbackRecordReqVO;
import com.usdt.system.domain.req.TransferOutReqVO;
import com.usdt.system.domain.req.VisitCustomerInfoReqVO;
import com.usdt.system.domain.req.VisitRecordReqVO;
import com.usdt.system.domain.req.VisitRegisterListExportReqVO;
import com.usdt.system.domain.req.VisitRegisterReqVO;
import com.usdt.system.domain.resp.BatchVisitRespVO;
import com.usdt.system.domain.resp.CallbackRecordRespVO;
import com.usdt.system.domain.resp.VisitCustomerInfoRespVO;
import com.usdt.system.domain.resp.VisitRecordRespVO;
import com.usdt.system.domain.resp.VisitRegisterListRespVO;
import com.usdt.system.domain.resp.VisitRegisterRespVO;
import com.usdt.system.dto.cp.VisitRegisterListExcelDTO;
import com.usdt.system.mapper.cp.VisitRegisterMapper;
import com.usdt.system.service.ISysDictTypeService;
import com.usdt.system.service.ISysUserService;
import com.usdt.system.service.cp.CallbackRecordService;
import com.usdt.system.service.cp.VisitCustomerInfoService;
import com.usdt.system.service.cp.VisitRecordService;
import com.usdt.system.service.cp.VisitRegisterService;

/**
 * <p>
 * 到访登记 服务实现类
 * </p>
 *
 * @author L
 * @since 2025-10-04
 */
@Service
public class VisitRegisterServiceImpl extends ServiceImpl<VisitRegisterMapper, VisitRegisterEntity> implements VisitRegisterService {
	
	private static final Integer Sales_Manager_Id = 100;
	private static final Integer Sales_Person_Id = 101;
	
	@Value("${sys.properties.ky.main_dept_id}")
	public String mainDeptId;
	
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private VisitCustomerInfoService visitCustomerInfoService;
    
    @Autowired
    private ISysDictTypeService dictTypeService;
    
    @Autowired
    private VisitRecordService visitRecordService;
    
    @Autowired
    private CallbackRecordService callbackRecordService;

	@Override
	public IPage<VisitRegisterListRespVO> list(String channel, String keyWord, String startDate, String endDate, String customerStatus, String userId,
			Integer pageNum, Integer pageSize){
		
		String currentDeptId = this.getCurrentDeptId();
		String currentUserId = this.getUserId();
		IPage<VisitRegisterListRespVO> page = baseMapper.findPageList(
				new Page<>(pageNum, pageSize),
				channel, keyWord, startDate, endDate, customerStatus, userId
				,currentDeptId,currentUserId
				);
		
		return page;
	}
	
	/** 获取当前人员：是否只查自己
	 * @return
	 */
	private String getUserId() {
		String result = UserAndDeptUtils.getCurrentUserId();
		SysUser sysUser = userService.selectUserByCpId(result);
		List<SysRole> roles = sysUser.getRoles();
		if(!CollectionUtils.isEmpty(roles)) {
			SysRole orElse = roles.stream().filter(e->(Sales_Manager_Id+"").equals(e.getRoleId()+"")).findAny().orElse(null);
			if(null!=orElse) {
				return null;
			}
		}
		return result;
	}

	/** 获取当前部门
	 * @return
	 */
	private String getCurrentDeptId() {
		String currentDeptId = UserAndDeptUtils.getCurrentDeptId();
		if(mainDeptId.equals(currentDeptId)) {
			currentDeptId=null;
		}
		return currentDeptId;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean insert(VisitRegisterReqVO vo) {
		VisitRegisterEntity visitRegisterEntity = BeanUtil.toBean(vo, VisitRegisterEntity.class);
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		
		visitRegisterEntity.setDeptId(currentUserIdAndDeptId.get("currentDeptId"));
		visitRegisterEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
		visitRegisterEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
		visitRegisterEntity.setCustomerStatus(
				StringUtils.isBlank(visitRegisterEntity.getCustomerStatus())?"1":visitRegisterEntity.getCustomerStatus());
		baseMapper.insert(visitRegisterEntity);
		if(!CollectionUtils.isEmpty(vo.getVisitCustomerList())) {
			List<VisitCustomerInfoReqVO> visitCustomerList = vo.getVisitCustomerList();
			visitCustomerList.forEach(e->{
				e.setId(null);			
				});
			insertOrUpdateVisitCustomerInfoList(visitRegisterEntity.getId(),
					visitRegisterEntity.getDeptId(), visitCustomerList);
		}
		return true;
	}

	/**新增或者修改线索客户
	 * @param id
	 * @param clueCustomerList
	 */
	private void insertOrUpdateVisitCustomerInfoList(Integer id, String deptId, List<VisitCustomerInfoReqVO> visitCustomerList) {
		List<VisitCustomerInfoEntity> list = new ArrayList<VisitCustomerInfoEntity>(visitCustomerList.size());
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		visitCustomerList.forEach(e->{
			VisitCustomerInfoEntity visitCustomerInfoEntity = BeanUtil.toBean(e, VisitCustomerInfoEntity.class);
			visitCustomerInfoEntity.setVisitId(id);
			visitCustomerInfoEntity.setDeptId(deptId);
			visitCustomerInfoEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
			visitCustomerInfoEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
			list.add(visitCustomerInfoEntity);
		});
		
		for (VisitCustomerInfoEntity visitCustomerInfoEntity : list) {
			//根据部门,手机号 查重
			List<VisitCustomerInfoEntity> checkList = visitCustomerInfoService.checkVisitCustomerInfoUniqueByDeptIdAndPhoneNumber(deptId,visitCustomerInfoEntity.getPhoneNumber(),visitCustomerInfoEntity.getId());
			if(!CollectionUtils.isEmpty(checkList)) {
				//查询项目
				List<SysDictData> projectData = dictTypeService.selectDictDataByType("project_manage");
				SysDictData project = projectData.stream().filter(e->deptId.equals(e.getDictValue())).findAny().orElse(null);
				throw new ServiceException("该线索在"+project.getDictLabel()+"项目已存在", -1);
			}
			visitCustomerInfoService.saveOrUpdate(visitCustomerInfoEntity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer update(Integer id,VisitRegisterReqVO vo) {
		VisitRegisterEntity visitRegisterEntity = baseMapper.selectById(id);
		BeanUtil.copyProperties(vo, visitRegisterEntity);
		visitRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		baseMapper.updateById(visitRegisterEntity);
		
		//删除
		visitCustomerInfoService.delByVisitId(id);
		if(!CollectionUtils.isEmpty(vo.getVisitCustomerList())) {
			insertOrUpdateVisitCustomerInfoList(id,visitRegisterEntity.getDeptId(), vo.getVisitCustomerList());
		}
		return id;
	}

	@Override
	public VisitRegisterRespVO detail(Integer id) {
		VisitRegisterEntity visitRegisterEntity = baseMapper.selectById(id);
		VisitRegisterRespVO visitRegisterRespVO = BeanUtil.toBean(visitRegisterEntity, VisitRegisterRespVO.class);
		
		//线索人员
		List<VisitCustomerInfoEntity> visitCustomerInfoEntityList =  visitCustomerInfoService.getVisitCustomerInfoByVisitId(id);
		if(!CollectionUtils.isEmpty(visitCustomerInfoEntityList)) {
			visitRegisterRespVO.setVisitCustomerList(BeanUtil.toBeans(visitCustomerInfoEntityList, VisitCustomerInfoRespVO.class)); 
		}
		
		//到访记录
		List<VisitRecordEntity> visitRecordList =  visitRecordService.getVisitRecordByVisitId(id);
		if(!CollectionUtils.isEmpty(visitRecordList)) {
			List<VisitRecordRespVO> list = BeanUtil.toBeans(visitRecordList, VisitRecordRespVO.class);
			for (int i = 0; i < list.size(); i++) {
				VisitRecordRespVO visitRecordRespVO = list.get(i);
				if(i==list.size()-1) {
					visitRecordRespVO.setNumStr("首访");
				}else {
					visitRecordRespVO.setNumStr((list.size()-i)+"访");
				}
				SysUser sysUser = userService.selectUserByCpId(visitRecordRespVO.getCreateBy());
				visitRecordRespVO.setCreateByName(sysUser.getNickName());
			}
			visitRegisterRespVO.setVisitRecordList(list);
		}
		
		//回访记录
		List<CallbackRecordEntity> callbackRecordList =  callbackRecordService.getCallbackRecordByVisitId(id);
		if(!CollectionUtils.isEmpty(callbackRecordList)) {
			for (CallbackRecordEntity callbackRecordEntity : callbackRecordList) {
				SysUser sysUser = userService.selectUserByCpId(callbackRecordEntity.getCreateBy());
				callbackRecordEntity.setCreateByName(sysUser.getNickName());
			}
			visitRegisterRespVO.setCallbackRecordList(BeanUtil.toBeans(callbackRecordList, CallbackRecordRespVO.class));   ;
		}
		
		//当前业务员
		SysUser sysUser = userService.selectUserByCpId(visitRegisterEntity.getCreateBy());
		visitRegisterRespVO.setCurrentUserName(sysUser.getNickName());
		visitRegisterRespVO.setCurrentUserId(sysUser.getCpUserid());
		return visitRegisterRespVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean transferOut(Integer id, TransferOutReqVO vo) {
		VisitRegisterEntity visitRegisterEntity = baseMapper.selectById(id);
		visitRegisterEntity.setCreateBy(vo.getOutUserId());
		visitRegisterEntity.setDeptId(vo.getOutDeptId());
		visitRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		baseMapper.updateById(visitRegisterEntity);
		
		visitCustomerInfoService.transferOut(id,vo.getOutUserId(),vo.getOutDeptId(),UserAndDeptUtils.getCurrentUserIdAndDeptId().get("currentUserId"));
		return true;
	}

	@Override
	public Boolean visitRecord(Integer id, VisitRecordReqVO vo) {
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		VisitRecordEntity visitRecordEntity = BeanUtil.toBean(vo, VisitRecordEntity.class);
		visitRecordEntity.setVisitId(id);
		visitRecordEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
		visitRecordEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
		visitRecordService.save(visitRecordEntity);
		
		return true;
	}

	@Override
	public Boolean callbackRecord(Integer id, CallbackRecordReqVO vo) {
		Map<String, String> currentUserIdAndDeptId = UserAndDeptUtils.getCurrentUserIdAndDeptId();
		CallbackRecordEntity callbackRecordEntity = BeanUtil.toBean(vo, CallbackRecordEntity.class);
		callbackRecordEntity.setVisitId(id);
		callbackRecordEntity.setCreateBy(currentUserIdAndDeptId.get("currentUserId"));
		callbackRecordEntity.setUpdateBy(currentUserIdAndDeptId.get("currentUserId"));
		callbackRecordService.save(callbackRecordEntity);
		return true;
	}

	@Override
	public List<VisitRegisterListExcelDTO> listExport(VisitRegisterListExportReqVO vo) {
		String currentDeptId = this.getCurrentDeptId();
		String currentUserId = this.getUserId();
		List<VisitRegisterListExcelDTO> list = baseMapper.findList(
				vo.getChannel(), 
				vo.getKeyWord(), 
				vo.getStartDate(), 
				vo.getEndDate(), 
				vo.getCustomerStatus(), 
				vo.getUserId()
				,currentDeptId,currentUserId
				);
		
		return CollectionUtils.isEmpty(list)?new ArrayList<VisitRegisterListExcelDTO>():list;
	}

	@Override
	public List<BatchVisitRespVO> getVisitByPhoneNumber(String phoneNumber, List<String> deptIds) {
		
		return baseMapper.getVisitByPhoneNumber(phoneNumber,deptIds);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean batchTransferOut(BatchTransferOutReqVO vo) {
		List<Integer> ids = vo.getIds();
		if(CollectionUtils.isEmpty(vo.getIds())){
			QueryWrapper<VisitRegisterEntity> query = new QueryWrapper<VisitRegisterEntity>();
			query.eq("dept_id", vo.getFromDeptId()).eq("create_by", vo.getFromUserId()).eq("is_del", false);
			List<VisitRegisterEntity> visitList = baseMapper.selectList(query);
			if(!CollectionUtils.isEmpty(visitList)) {
				ids = visitList.stream().map(e->e.getId()).toList();
			}
		}
		if(!CollectionUtils.isEmpty(ids)) {
			VisitRegisterEntity visitRegisterEntity = new VisitRegisterEntity();
			visitRegisterEntity.setDeptId(vo.getOutDeptId());
			visitRegisterEntity.setCreateBy(vo.getOutUserId());
			visitRegisterEntity.setUpdateBy(UserAndDeptUtils.getCurrentUserId());
			
			QueryWrapper<VisitRegisterEntity> q = new QueryWrapper<VisitRegisterEntity>();
			q.in("id", ids);
			baseMapper.update(visitRegisterEntity, q);
			visitCustomerInfoService.batchTransferOut(ids,vo.getOutUserId(),vo.getOutDeptId());
		}
		return true;
	}

	@Override
	public IPage<BatchVisitRespVO> batchVisitTransferOutPage(List<String> sourceList, String userId, List<String> deptIds,String phoneNumber,
			Integer pageNum, Integer pageSize) {
		
		return baseMapper.batchVisitTransferOutPage(new Page<>(pageNum, pageSize)
							,sourceList,
							userId,
							deptIds,
							phoneNumber);
	}
}
